package com.example.iqiyitest.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;

@SuppressLint("SimpleDateFormat")
public class XsUtils {

	private static final String DB_NAME = "xs_movies.db";
	private static final int DB_VERSION = 1;

	
	/**
	 * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	/**
	 * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static String getSdcardPath(Context context) {
		File sdcard = null;
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			sdcard = Environment.getExternalStorageDirectory();
		} else if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
				|| !Environment.isExternalStorageRemovable()) {
			if (context.getExternalCacheDir() != null) {
				if (!context.getExternalCacheDir().exists()) {
					context.getExternalCacheDir().mkdirs();
				}
				sdcard = context.getExternalCacheDir();
			}
		}
		if (sdcard == null) {
			sdcard = context.getCacheDir();
		}
		return sdcard.getPath();
	}


	/**
	 * Format milliseconds to hh:mm:ss
	 */
	public static String formatMillisecond(long millisecond) {
		long time = millisecond / 1000;
		if (time <= 0) {
			return "00:00:00";
		}

		return String.format(Locale.getDefault(), "%02d:%02d:%02d", time / 60 / 60, time / 60 % 60, time % 60);
	}

	// 播放时间格式
	public static String FormatTime(int j) {
		String str = "";
		if (j < 10) {
			str = String.format(Locale.getDefault(), "0%d", j);
		} else {
			str = String.format(Locale.getDefault(), "%d", j);
		}

		return str;
	}

	public static String getZoomImageName(String imageName) {
		return "z_" + imageName;
	}

	/**
	 * 获取图片后缀名
	 * 
	 * @param url
	 * @return
	 */
	public static String getPostfix(String url) {
		String postfix = null;
		if (!XsUtils.isNull(url) && url.lastIndexOf(".") > 0) {
			postfix = url.substring(url.lastIndexOf(".")).toLowerCase(Locale.getDefault());
		}
		return postfix;
	}

	
	public static String getThumbImageName(Video movie) {
		return getImageNameFromUrl(movie.getPicLocal());
	}

	public static String getAdpicImageName(Video movie) {
		return getImageNameFromUrl(movie.getPicLocal());
	}

	public static String getImageNameFromUrl(String url) {
		if (!isNull(url) && (url.toLowerCase(Locale.getDefault()).endsWith(".jpg")
				|| url.toLowerCase(Locale.getDefault()).endsWith(".png")
				|| url.toLowerCase(Locale.getDefault()).endsWith(".jpeg"))) {
			return url.substring(url.lastIndexOf("/") + 1);
		}
		return "";
	}

	/**
	 * url特殊字符处理
	 * 
	 * @param url
	 * @return
	 */
	public static String formatUrl(String url) {
		try {
			url = url.replaceAll(" ", "%20");
			url = URLEncoder.encode(url, "utf-8").replaceAll("\\+", "%20");
			url = url.replaceAll("%3A", ":").replaceAll("%2F", "/");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return url;
	}

	/**
	 * url特殊字符处理
	 * 
	 * @param url
	 * @return
	 */
	public static String formatImageUrl(String url) {
		String _url = null;
		try {
			_url = URLEncoder.encode(url, "utf-8").replaceAll("\\+", "%20");
			_url = _url.replaceAll("%3A", ":").replaceAll("%2F", "/");
		} catch (Exception e) {
			e.printStackTrace();
		}
		;
		return _url;
	}

	/**
	 * 判断字符串是否为空
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNull(String str) {
		return str == null || "".equals(str);
	}

	/**
	 * json转码，将Unicode转为utf-8
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static String transcodeJson(String jsonStr) {
		byte[] converttoBytes;
		String res = null;
		try {
			if (!isNull(jsonStr)) {
				converttoBytes = jsonStr.getBytes("UTF-8");
				res = new String(converttoBytes, "UTF-8");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return res;
	}

	public static String getDateCompleteStr() {
		Date d = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		return df.format(d);
	}

	public static String getDateSimpleStr() {
		Date d = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		return df.format(d);
	}
	
	
	
	/**
	 * 获取网落图片资源
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getHttpBitmap(String url) {
		URL myFileURL;
		Bitmap bitmap = null;
		try {
			myFileURL = new URL(url);
			// 获得连接
			HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();
			// 设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
			conn.setConnectTimeout(6000);
			// 连接设置获得数据流
			conn.setDoInput(true);
			// 不使用缓存
			conn.setUseCaches(false);
			// 这句可有可无，没有影响
			// conn.connect();
			// 得到数据流
			InputStream is = conn.getInputStream();
			// 解析得到图片
			bitmap = BitmapFactory.decodeStream(is);
			// 关闭数据流
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;

	}

	
	

	public static Bitmap getBitmapFromFile(String path) throws FileNotFoundException {
		File file = new File(path);
		Bitmap bitmap = null;
		if (file != null && file.exists()) {
			long fileLength = file.length();
			BitmapFactory.Options options = new BitmapFactory.Options();
			if (fileLength > (200 * 1024)) {
				options.inSampleSize = 2; // 图片宽高都为原来的二分之一，即图片为原来的四分之一
				bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
			} else {
				bitmap = BitmapFactory.decodeStream(new FileInputStream(file), null, options);
			}
		}
		return bitmap;
	}

	// 获取build.prop中的指定属性 ro.product.model
	public static String getProductModel() {
		BufferedReader br = null;
		InputStream is = null;
		FileInputStream in = null;
		try {
			in = new FileInputStream(new File("/system/build.prop"));
			is = new BufferedInputStream(in);
			br = new BufferedReader(new InputStreamReader(is));
			String strTemp = "";
			while ((strTemp = br.readLine()) != null) {// 如果文件没有读完则继续
				if (strTemp.indexOf("ro.product.model") != -1)
					return strTemp.substring(strTemp.indexOf("=") + 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
				if (is != null)
					is.close();
				if (in != null)
					in.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	@SuppressWarnings("deprecation")
	public static int getWinWidth(Context context) {
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		int width = wm.getDefaultDisplay().getWidth();
		return width;
	}
	public static int getWinHight(Context context) {
//		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//		int width = wm.getDefaultDisplay().getHeight();
//		return width;
		
		WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Point point = new Point();
		wm.getDefaultDisplay().getRealSize(point);
		return point.x;
	}

	private static int itemMarginLeft = 0;




	public static boolean equalAndNotNull(String str1, String str2) {
		return !isNull(str1) && str1.equals(str2);
	}
	
	/**
     * 获取所有包名的ResolveInfo，即有可点图标的Activity。按名称正序。
     * @param context Context
     * @param packages 包括的包名
     * @return ResolveInfo List，按名称正序。
     */
    public static List<ResolveInfo> getResolveInfos(Context context,List<String> packages) {
        PackageManager packageManager = context.getPackageManager();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> resolveInfoList = packageManager
                .queryIntentActivities(mainIntent, 0);
        List<ResolveInfo> res = new ArrayList<ResolveInfo>();
        if (resolveInfoList == null)
            return res;

            Iterator<ResolveInfo> it = resolveInfoList.iterator();
            while (it.hasNext()) {
                ResolveInfo resolveInfo = it.next();
                if(packages.contains(resolveInfo.activityInfo.packageName)){
                	res.add(resolveInfo);
                }
            }
        Collections.sort(res, new ResolveInfo.DisplayNameComparator(packageManager));
        return res;
    }
    
    
    
   
   
}
